package com.hy.generator.common.exception;


import com.hy.generator.common.api.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;


@Slf4j
@RestControllerAdvice
public class DefaultExceptionHandler {

    @Autowired
    private MultipartProperties multipartProperties;




    /**
     * 200 业务异常
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public ApiResult<Void> businessException(BusinessException e) {
        log.warn("[全局异常] - 业务异常 {}", e.getMessage(), e);
        return ApiResult.fail(e.getMessage());
    }


    /**
     * 处理上传的文件超过指定大小的异常
     *
     * @param ex 文件大小超过指定异常
     */
    @ExceptionHandler(value = {MaxUploadSizeExceededException.class})
    public ApiResult<Void> processFileTooLarge(MaxUploadSizeExceededException ex) {
        log.error("文件过大", ex);
        return ApiResult.fail("文件大小必须小于(" + multipartProperties.getMaxFileSize().toMegabytes() + "MB)");
    }



    /**
     * 统一异常处理
     *
     * @param exception exception
     */
    @ExceptionHandler(value = {Exception.class})
    public ApiResult<Void> processException(RuntimeException exception) {
        log.error(exception.getMessage(), exception);
        return ApiResult.fail(ApiResult.INTERNAL_FAIL_CODE, exception.getMessage());
    }

}



